<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>用户名：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.userName"
                        clearable
                        placeholder="用户名"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>账号类型：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.groupOwner"
                        clearable
                        placeholder="请选择账号类型"
                    >
                        <el-option label="主账号" :value="true"></el-option>
                        <el-option label="子账号" :value="false"></el-option>
                    </el-select>
                </div>
            </div>
            <div class="search-item">
                <label>昵称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="昵称"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>机构：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.groupId"
                        filterable
                        clearable
                        placeholder="请选择机构"
                        remote
                        reserve-keyword
                        :remote-method="loadGroup"
                        :loading="flag.groupFlag"
                    >
                        <el-option
                            v-for="item in groups"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="clickAdd('添加机构管理员', () => loadGroup(null, true))"
            >新增机构管理员
            </el-button>
            <el-button
                type="warning"
                style="margin-bottom: 2em"
                icon="el-icon-lock"
                :disabled="selectDisable"
                @click="batchLock(false)"
            >批量禁用
            </el-button>
            <el-button
                type="info"
                style="margin-bottom: 2em"
                icon="el-icon-unlock"
                :disabled="selectDisable"
                @click="batchLock(true)"
            >批量启用
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                    prop="header"
                    label="头像"
                    width="80"
                    align="center"
                >
                    <template slot-scope="scope">
                        <el-avatar :src="coverImage(scope.row.header)"
                        >{{ scope.row.name }}
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="账号类型" width="130">
                    <template slot-scope="scope">
                        <p>{{ scope.row.groupOwner ? "主账号" : "子账号" }}</p>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="昵称（名字）"
                    width="200"
                ></el-table-column>
                <el-table-column
                    prop="account"
                    label="用户名"
                    width="200"
                ></el-table-column>
                <el-table-column
                    prop="mobile"
                    label="手机号"
                    width="120"
                ></el-table-column>
                <el-table-column
                    prop="groupModel.name"
                    label="机构"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    prop="groupModel.expireTime"
                    label="过期时间"
                    width="140"
                ></el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    width="180"
                ></el-table-column>
                <el-table-column
                    label="操作"
                    width="200"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            :loading="scope.row.opLoading"
                            class="warning"
                            size="mini"
                            type="text"
                            icon="el-icon-refresh-right"
                            @click="resetPass(scope.row)"
                        >重置密码
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="
                                clickSimpleEdit(
                                    scope.row,
                                    '机构管理员信息编辑',
                                    () => loadGroup(null, true)
                                )
                            "
                        >编辑
                        </el-button>
                        <el-button
                            v-if="scope.row.userStatus === 'normal'"
                            :loading="scope.row.opLoading"
                            class="warning"
                            size="mini"
                            type="text"
                            icon="el-icon-lock"
                            @click="changeUserStatus(scope.row, false)"
                        >禁用
                        </el-button>
                        <el-button
                            v-if="scope.row.userStatus === 'lock'"
                            :loading="scope.row.opLoading"
                            size="mini"
                            type="text"
                            icon="el-icon-unlock"
                            @click="changeUserStatus(scope.row, true)"
                        >启用
                        </el-button>
                        <el-button
                            v-if="!scope.row.groupId"
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="toReBind(scope.row, '关联机构')"
                        >关联机构
                        </el-button>
                        <el-button
                            v-if="scope.row.groupId"
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="unBind(scope.row)"
                        >取消机构关联
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            custom-class="one-dialog"
            @close="
                () => {
                    base64Icon = null;
                }
            "
        >
            <el-form
                ref="dataForm"
                :key="dataForm.id"
                :model="dataForm"
                label-width="8em"
                :rules="dataFormRuleComputed"
                class="table-edit-from exam-form"
            >
                <el-form-item label="账户类型" prop="groupOwner">
                    <el-switch
                        v-model="dataForm.groupOwner"
                        active-text="主账号"
                        inactive-text="子账号"
                        :disabled="!dataForm.addAction"
                    >
                    </el-switch>
                </el-form-item>
                <el-form-item label="机构" prop="groupId">
                    <el-select
                        v-model="dataForm.groupId"
                        filterable
                        clearable
                        placeholder="请选择机构"
                        remote
                        reserve-keyword
                        :remote-method="v => loadGroup(v, true)"
                        :loading="flag.groupFlag"
                    >
                        <el-option
                            v-for="item in groupsForm"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名（昵称）" prop="name">
                    <el-input v-model="dataForm.name"></el-input>
                </el-form-item>
                <el-form-item label="头像" prop="header" class="header">
                    <el-upload
                        class="avatar-uploader"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        accept=".jpg,.png,.jpeg"
                        :auto-upload="false"
                        :on-change="headerChange"
                    >
                        <img
                            v-if="base64Header || dataForm.header"
                            :src="base64Header || coverImage(dataForm.header)"
                            class="avatar"
                        />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item
                    v-if="!dataForm.groupOwner"
                    label="手机号"
                    prop="mobile"
                >
                    <el-input
                        v-model="dataForm.mobile"
                        :disabled="!dataForm.addAction"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    v-if="dataForm.groupOwner && dataForm.addAction"
                    label="账号"
                    prop="account"
                >
                    <el-input v-model="dataForm.account"></el-input>
                </el-form-item>
                <el-form-item
                    v-if="dataForm.groupOwner && dataForm.addAction"
                    label="密码"
                    prop="pass"
                >
                    <el-input v-model="dataForm.pass"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="save"
                >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Fetch from "@/api/request.js";
import {TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {get, put, post} from "@/api/request";
import {unBindGroupAdmin} from "@/api/user";
import groupBindComponent from "@/views/models/vrs/group/groupBind";
import {ossUpload, elUploadHandler} from "@/utils/file.js";

export default {
    name: "GroupAdminList",
    components: {groupBindComponent},
    mixins: [TablePage],
    data() {
        return {
            queryData: {
                name: "",
                mobile: "",
                groupOwner: null,
                groupId: null,
                searchCount: true,
                orders: [
                    {
                        asc: false,
                        column: "created_time"
                    }
                ]
            },
            base64Header: null,
            initAddForm: {
                id: null,
                mobile: null,
                name: null,
                header: null,
                groupId: null,
                groupOwner: false,
                account: null,
                pass: null
            },
            groups: [],
            groupsForm: [],
            flag: {
                groupFlag: false
            }
        };
    },
    computed: {
        ...mapState({}),
        dataFormRuleComputed() {
            var data = {
                name: [
                    {
                        required: true,
                        message: "请输入姓名",
                        trigger: "blur"
                    }
                ],
                groupId: [
                    {
                        required: true,
                        message: "请选择机构",
                        trigger: "change"
                    }
                ]
            };
            if (!this.dataForm.addAction) return data;
            if (this.dataForm.groupOwner) {
                data.account = [
                    {
                        required: true,
                        message: "请输入账号",
                        trigger: "blur"
                    }
                ];
                data.pass = [
                    {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!/^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,20}$/.test(value)) {
                                callback(new Error("请输入6-20位密码,同时包含大小写字母及数字"));
                            } else {
                                callback();
                            }
                        }
                    }
                ];
            } else {
                data.mobile = [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: "blur"
                    }
                ];
            }
            return data;
        }
    },
    watch: {
        "dataForm.addAction"() {
            this.$refs.dataForm.validate()
        }
    },
    created() {
        this.loadGroup();
    },
    mounted() {
    },
    methods: {
        search(queryData) {
            this.loadTable("/user/sys/group/group-admin-page", queryData);
        },
        async batchLock(status) {
            if (!status) {
                await this.$confirm("确定禁用这些账号吗？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                });
            }
            this.tableData
                .filter(v => this.tableSelect.includes(v.id))
                .forEach(v => this.changeUserStatus(v, status));
        },
        changeUserStatus(data, status) {
            data.opLoading = true;
            post(`/user/cu/admin/user/enable/${status}/${data.id}`)
                .then(res => {
                    data.userStatus = status ? "normal" : "lock";
                })
                .finally(() => {
                    data.opLoading = false;
                });
        },
        async resetPass(row) {
            let newPassword = "tk123456";
            await this.$confirm(
                "确定将密码重置为" + newPassword + "吗?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            );
            post(`/user/cu/user/change/password-admin/${row.id}`, {
                newPassword: newPassword
            })
                .then(() => {
                    this.$message.success("重置成功");
                })
                .catch(e => {
                    this.$message.error("重置失败");
                });
        },
        headerChange(file, fileList) {
            if (fileList.length > 1) {
                fileList.splice(0, 1);
            }
            const elFile = fileList[0];
            file = fileList[0].raw;
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file);
            ossUpload("cdn", file.name, file, p => {
                elFile.percentage = p * 100;
                elFile.status = "uploading";
            }).then(result => {
                this.dataForm.header = result;
                elFile.status = "done";
            });
        },
        loadGroup(query, form) {
            return this.flagPromise(
                get("/user/sys/group/list", {
                    name: query,
                    size: 1000
                }).then(res => {
                    if (form) this.groupsForm = res;
                    else this.groups = res;
                    return res;
                }),
                "groupFlag"
            );
        },
        unBind(data) {
            unBindGroupAdmin({userId: data.id}).then(res => {
                this.search();
            });
        },
        save() {
            this.$refs.dataForm.validate((check) => {
                if (check) {
                    if (this.dataForm.id === null && !this.dataForm.addAction && !/^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,20}$/.test(this.dataForm.pass)) {
                        this.$message.error("请输入6-20位密码,同时包含大小写字母及数字");
                        return
                    }
                    this.formDataSave(
                        "/user/sys/group/groupAdmin/update",
                        undefined,
                        () => {
                            this.base64Header = null;
                        }
                    )
                }

            })

        }
    }
};
</script>

<style lang="scss" scoped></style>
<style lang="css">
.header .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.header .avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.header .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 4.58rem;
    height: 4.58rem;
    line-height: 4.58rem;
    text-align: center;
}

.header .avatar {
    width: 4.58rem;
    height: 4.58rem;
    display: block;
}
</style>
